package com.fx.ruankao.controller;

import com.fx.ruankao.entity.ExamRecord;
import com.fx.ruankao.service.ExamRecordService;
import com.fx.ruankao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * 考试记录控制器
 */
@RestController
@RequestMapping("/api/admin/exams")
@Validated
public class ExamRecordController {
    
    @Autowired
    private ExamRecordService examRecordService;
    
    /**
     * 新增考试记录
     */
    @PostMapping
    public Result insert(@RequestBody ExamRecord examRecord) {
        try {
            int result = examRecordService.insert(examRecord);
            if (result > 0) {
                return Result.success("新增考试记录成功");
            } else {
                return Result.error("新增考试记录失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除考试记录
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable @Min(1) Long id) {
        try {
            int result = examRecordService.deleteById(id);
            if (result > 0) {
                return Result.success("删除考试记录成功");
            } else {
                return Result.error("删除考试记录失败或记录不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新考试记录
     */
    @PutMapping
    public Result update(@RequestBody ExamRecord examRecord) {
        try {
            int result = examRecordService.update(examRecord);
            if (result > 0) {
                return Result.success("更新考试记录成功");
            } else {
                return Result.error("更新考试记录失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询考试记录
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable @Min(1) Long id) {
        try {
            ExamRecord examRecord = examRecordService.selectById(id);
            if (examRecord != null) {
                return Result.success(examRecord);
            } else {
                return Result.error("未找到考试记录");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询考试记录
     */
    @GetMapping("/user/{userId}")
    public Result selectByUserId(@PathVariable @Min(1) Long userId) {
        try {
            List<ExamRecord> examRecords = examRecordService.selectByUserId(userId);
            return Result.success(examRecords);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据试卷ID查询考试记录
     */
    @GetMapping("/paper/{paperId}")
    public Result selectByPaperId(@PathVariable @Min(1) Long paperId) {
        try {
            List<ExamRecord> examRecords = examRecordService.selectByPaperId(paperId);
            return Result.success(examRecords);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除考试记录
     */
    @DeleteMapping("/batch")
    public Result batchDelete(@RequestBody Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error("请选择要删除的考试记录");
            }
            int result = examRecordService.batchDelete(ids);
            if (result > 0) {
                return Result.success("批量删除考试记录成功");
            } else {
                return Result.error("批量删除考试记录失败");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新考试成绩
     */
    @PutMapping("/{id}/score/{score}")
    public Result updateScore(@PathVariable @Min(1) Long id, @PathVariable @Min(0) Integer score) {
        try {
            boolean result = examRecordService.updateScore(id, score);
            if (result) {
                return Result.success("更新考试成绩成功");
            } else {
                return Result.error("更新考试成绩失败或记录不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新考试状态
     */
    @PutMapping("/{id}/status/{status}")
    public Result updateStatus(@PathVariable @Min(1) Long id, @PathVariable Integer status) {
        try {
            boolean result = examRecordService.updateStatus(id, status);
            if (result) {
                return Result.success("更新考试状态成功");
            } else {
                return Result.error("更新考试状态失败或记录不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 开始考试
     */
    @PostMapping("/start")
    public Result startExam(@RequestBody @Validated StartExamRequest request) {
        try {
            if (request.getUserId() == null || request.getUserId() <= 0) {
                return Result.error("用户ID不能为空且必须大于0");
            }
            if (request.getPaperId() == null || request.getPaperId() <= 0) {
                return Result.error("试卷ID不能为空且必须大于0");
            }
            
            // 检查用户是否已经参加过该试卷的考试
            ExamRecord existingRecord = examRecordService.selectByUserIdAndPaperId(
                    request.getUserId(), request.getPaperId());
            if (existingRecord != null && existingRecord.getStatus() > 0) {
                return Result.error("您已经参加过该考试");
            }
            
            // 创建新的考试记录或更新现有记录
            ExamRecord examRecord;
            if (existingRecord != null) {
                examRecord = existingRecord;
            } else {
                examRecord = new ExamRecord();
                examRecord.setUserId(request.getUserId());
                examRecord.setPaperId(request.getPaperId());
            }
            examRecord.setStatus(1); // 设置状态为进行中
            
            if (existingRecord != null) {
                examRecordService.update(examRecord);
            } else {
                examRecordService.insert(examRecord);
            }
            
            return Result.success(examRecord, "开始考试成功");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 提交考试
     */
    @PostMapping("/{id}/submit")
    public Result submitExam(@PathVariable @Min(1) Long id) {
        try {
            // 更新考试状态为已完成
            boolean result = examRecordService.updateStatus(id, 2);
            if (result) {
                return Result.success("提交考试成功");
            } else {
                return Result.error("提交考试失败或记录不存在");
            }
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 开始考试请求参数
     */
    public static class StartExamRequest {
        @Min(1)
        private Long userId;
        @Min(1)
        private Long paperId;
        
        // getter和setter
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Long getPaperId() { return paperId; }
        public void setPaperId(Long paperId) { this.paperId = paperId; }
    }
    

}